package com.bitejiuyeke.forum.controller;

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.config.AppConfig;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IUserService;
import com.bitejiuyeke.forum.utils.MD5Util;
import com.bitejiuyeke.forum.utils.StringUtil;
import com.bitejiuyeke.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-11-30
 * Time: 15:26
 */
//对controller进行api说明
@Api(tags = "用户相关接口")
//日志注解
@Slf4j
//一个返回数据的controller
@RestController
//路由映射
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     *
     * @param username       用户名
     * @param nickname       名称
     * @param password       密码
     * @param passwordRepeat 重复密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("名称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //校验密码与重复密码是否相同
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5(password, salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        //调用service
        userService.createNormalUser(user);
        return AppResult.success();


    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request, @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        //调用service 中的登录方法，返回User对象
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //登录成功把User对象设置到Session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户ID") @RequestParam(value = "id", required = false) Long id) {
        //id为空，去session中获取
        //定义返回的user
        User user = null;
        if (id == null) {
            HttpSession session = request.getSession(false);
//            //判断session和用户信息是否有效
//            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
//                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
//
//            }
            // 从session中获取用户信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            user = userService.selectById(id);
        }
        // 判断用户信息是否为空
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //返回正常结果
        return AppResult.success(user);

    }
    @ApiOperation("用户退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session != null){
            log.info("退出成功");
            //销毁session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     *
     * @param username
     * @param nickname
     * @param gender
     * @param email
     * @param phoneNum
     * @param remark
     * @return
     */
    @ApiOperation("修改用户信息")
@PostMapping("/modifyInfo")
    public  AppResult modifyInfo(HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                 @ApiParam("用户昵称") @RequestParam(value = "nickname",required = false)  String nickname,
                                 @ApiParam("性别") @RequestParam(value = "gender",required = false)   Byte gender,
                                 @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                 @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @ApiParam("个人简介") @RequestParam(value = "remark",required = false)String remark ){
if(StringUtil.isEmpty(username) &&  StringUtil.isEmpty(nickname) && gender == null
        && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
        && StringUtil.isEmpty(remark) && gender ==null){
    //返回错误信息
    return AppResult.failed("修改信息不能为空");
        }
//从session中获取用户id
        HttpSession session = request.getSession(false);
      User user =(User)  session.getAttribute(AppConfig.USER_SESSION);

      //封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        //调用service方法
        userService.modifyInfo(updateUser);
        //查询最新用户信息
        user =userService.selectById(user.getId());

        //将用户信息存入session
        session.setAttribute(AppConfig.USER_SESSION,user);

        return AppResult.success(user);
    }


@ApiOperation("修改密码")
@PostMapping("/modifyPwd")
    public  AppResult modifyPassword(HttpServletRequest  request,
 @ApiParam("旧密码") @RequestParam(value = "oldPassword")  @NonNull  String oldPassword,
 @ApiParam("新密码") @RequestParam(value = "newPassword") @NonNull String newPassword,
 @ApiParam("确认密码") @RequestParam(value = "passwordRepeat")  @NonNull String passwordRepeat){
 // 校验，新密码与确认密码是否相同
    if (!newPassword.equals(passwordRepeat)) {
        // 返回错误信息
        return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
    }
    // 获取用户信息

    HttpSession session = request.getSession(false);
    User user =(User)  session.getAttribute(AppConfig.USER_SESSION);
    // 调用service方法
    userService.modifyPassword(user.getId(), newPassword, oldPassword);
     //销毁session
    if(session != null)
    {
        session.invalidate();
    }
    // 返回成功信息
        return  AppResult.success();
    }

}
